<?php
namespace app\api\controller;
/**
 * 文件上传类
 */
use think\Controller;

class Upload extends Controller {

	public function _initialize() {
		//判断是否是后台登录
		if (!session('?admin')) {
			echo json_encode(['status' => 'n', 'info' => '你还没有登录']);
			exit;
		}
	}

	public function upload() {
		if (IS_POST) {
			$auth = new \Qiniu\Auth(C('AccessKey'), C('SecretKey'));
			$upToken = $auth->uploadToken(C('bucket'));

			$uploadMgr = new \Qiniu\Storage\UploadManager();
			//自定义文件名
			$key = I('post.db/s', 'Undefined') . '_' . I('post.id/d', 'Undefined') . '.png';

			//删除已经存在的图片
			$bucketMgr = new \Qiniu\Storage\BucketManager($auth);
			$bucketMgr->delete(C('bucket'), $key);

			list($ret, $err) = $uploadMgr->putFile($upToken, $key, $_FILES['file']['tmp_name']);

			if ($err) {
				return [
					'status' => 'n',
					'info' => '图片上传失败',
				];
			} else {
				//加入数据库
				$url = C('qn_url') . $ret['key'];
				$Model = M(I('post.db/s'));
				$data = [
					I('field/s', 'img') => $url,
					'update_time' => NOW_TIME,
				];
				$res = $Model->where(['id' => I('post.id/d')])->setField($data);
				$result = [
					'status' => $res ? 'y' : 'n',
				];
				if ($res) {
					$result['img_url'] = $url;
				} else {
					$result['info'] = '数据保存错误';
				}
				return $result;
			}
		} else {
			return ['status' => 'n', 'info' => '请求方式错误'];
		}
	}
}
